import logging
from typing import List, Optional

from app.utils import str_utils

from app.admin.db import tenant_crud
from app.admin.schemas.tenant import TenantCreate, TenantUpdate,TenantQuery
from app.db.session import AsyncSessionLocal
from app.models.tenant import Tenant
from app.utils.date_utils import (
    get_current_time
)

# 配置日志
logger = logging.getLogger(__name__)


class TenantService:
    """
    租户服务类，处理租户相关的业务逻辑
    """

    async def get_tenant(self, tenant_id: str) -> Optional[Tenant]:
        """
        根据租户ID获取租户
        """
        async with AsyncSessionLocal() as db:
            return await tenant_crud.get_tenant(db, tenant_id)

    async def get_tenant_by_code(self, code: str) -> Optional[Tenant]:
        """
        根据租户编码获取租户
        """
        async with AsyncSessionLocal() as db:
            return await tenant_crud.get_tenant_by_code(db, code)

    async def get_tenants(self, query: TenantQuery) -> List[Tenant]:
        """
        获取租户列表，支持按条件筛选
        """
        async with AsyncSessionLocal() as db:
            return await tenant_crud.get_tenants(db, query)

    async def create_tenant(self, tenant: TenantCreate) -> Tenant:
        """
        创建新租户
        """
        tenant.id = str_utils.generate_uuid_without_hyphen()
        async with AsyncSessionLocal() as db:
            return await tenant_crud.create_tenant(db=db, tenant=tenant)

    async def update_tenant(self, tenant_id: str, tenant_update: TenantUpdate) -> Optional[Tenant]:
        """
        更新租户信息
        """
        tenant_update.update_at = get_current_time()
        async with AsyncSessionLocal() as db:
            return await tenant_crud.update_tenant(db, tenant_id=tenant_id, tenant_update=tenant_update)

    async def delete_tenant(self, tenant_id: str) -> bool:
        """
        删除租户
        """
        async with AsyncSessionLocal() as db:
            return await tenant_crud.delete_tenant(db, tenant_id)

    async def check_code_exists(self, code: str) -> bool:
        """
        检查租户编码是否已存在
        """
        tenant = await self.get_tenant_by_code(code)
        return tenant is not None


# 创建全局租户服务实例
tenant_service = TenantService()
